<template>
  <van-nav-bar left-arrow fixed @click-left="onClickLeft"/>
  <van-tabs scrollspy color="rgb(240, 136, 17)">
    <van-tab title="商品">
      <!-- 1.轮播图 -->
      <van-swipe class="my-swipe" :autoplay="3000" width="375" height="375">
        <van-swipe-item
        v-for="(item,index) in swiperImgs"
        :key="index">
      <img :src="item">
    </van-swipe-item>
      </van-swipe>
      <!-- 2.商品售卖信息 -->
      <van-cell class="salesInfo" :border="false">
        <!-- 商品信息一 -->
        <template #title>
          <div class="price">
          <!-- 商品价格 -->
          <span>￥{{storeInfo?.price}}</span>
          <!-- 分享商品 -->
          <van-icon class="share" name="share-o" size="22px"></van-icon>
          </div>
          <!-- 商品标题 -->
          <div class="title" v-text="storeInfo?.store_name"></div>
        </template>
        <!-- 商品信息二 -->
        <template #label>
          <!-- 商品原价 --> 
          <span>原价￥{{storeInfo?.ot_price}}</span>
          <!-- 商品库存 -->
          <span>库存:{{storeInfo?.stock + storeInfo?.unit_name}}</span>
          <!-- 商品销量 -->
          <span>销量:{{storeInfo?.fsales}}</span>
        </template>
      </van-cell>
      <!-- 3.商品规格 -->
      <van-cell class="sku-window" is-link 
      @click="handlePopup">
        <template #title>
          <span>已选择：{{ sku }}</span>
        </template>
      </van-cell>
      <van-popup v-model:show="specStatus.show"
      position="bottom">
      <van-cell-group>
        <!-- 头部商品信息 -->
        <van-cell class="pop-header">
          <img :src="specDetail?.image" />
          <div class="info">
            <p class="title" v-text="storeInfo?.store_name"></p>
            <p class="price">￥{{ specDetail?.price }}</p>
            <p class="stock">库存:{{ specDetail?.stock }}</p>
          </div>
        </van-cell>
        <!-- 规格选择 -->
        <van-cell class="spec" v-for="(attr,index) in productAttr" :key="attr.id">
          <p v-text="attr.attr_name"></p>
          <span class="tag" v-for="value in attr.attr_values" :key="value"
          v-text="value" :class="{ active: specStatus.spec[index] === value }"
          @click="handTag(value, index)"></span>
        </van-cell>
        <!-- 数量选择 -->
        <van-cell class="number" title="数量">
          <van-stepper v-model="specStatus.buyCount" min="1" :max="specDetail?.stock"/> 
        </van-cell>
      </van-cell-group>
      </van-popup>
    </van-tab>
    <van-tab title="评价" class="comment"> 
      <van-cell-group>
        <!-- 1.总体评价 -->
        <van-cell :title="userCounts" is-link :value="goodRate"
        :to="{
          name: 'comment',
          params: {
            productId
          }
          }">
        </van-cell>
        <!-- 2.评价列表-->
        <comment-item :reply="reply" v-if="commentCounts !== 0">
        </comment-item>
      </van-cell-group>
    </van-tab>
    <van-tab title="推荐">
      <van-cell class="recommend">
        <p class="title">推荐商品</p>
        <van-grid :column-num="3" :border="false" :center="false">
          <van-grid-item v-for="item in recommendGoods" :key="item.id"
          :to="{
            name: 'product',
            params: {
              productId: item.id
            }
          }">
            <van-image :src="item.image"></van-image>
            <p v-text="item.store_name"></p>
            <span>￥{{item.price}}</span>
          </van-grid-item>
        </van-grid>
      </van-cell>
    </van-tab>
    <van-tab title="详情">
      <div class="description" v-html="storeInfo?.description">
      </div>
    </van-tab>
  </van-tabs>
  <!-- 加入购物车处理 -->
  <van-action-bar>
    <van-action-bar-icon icon="chat-o" text="客服" color="#ee0a24" />
    <van-action-bar-icon icon="cart-o" text="购物车"  to="/car"/>
    <van-action-bar-icon icon="star" text="已收藏" color="#ff5000" />
    <van-action-bar-button type="warning" text="加入购物车" @click="handleAdd"/>
    <van-action-bar-button type="danger" text="立即购买"  to="/car"/>
  </van-action-bar>

</template>
<script setup>
import { NavBar as VanNavBar, CellGroup as VanCellGroup, SwipeItem as VanSwipeItem,
  Cell as VanCell, Popup as VanPopup, Tab as VanTab, Tabs as VanTabs, Grid as VanGrid,
  GridItem as VanGridItem, Image as VanImage, Stepper as VanStepper,  Swipe as VanSwipe,
  Icon as VanIcon, ActionBar as VanActionBar, ActionBarIcon as VanActionBarIcon,
  ActionBarButton as VanActionBarButton } from 'vant'
import { addCart  } from '@/api/cart.js'
import CommentItem from '@/components/commentItem.vue'
import { getProductsDetails } from '@/api/product.js'
import { computed } from '@vue/reactivity';
import { ref } from 'vue';
import { onBeforeRouteUpdate, useRouter } from 'vue-router'
import store from '../../store';
import { Toast } from 'vant';
const router = useRouter()

// 接收productId从路由传过来的
const { productId } = defineProps({
  productId: {
    type: String,
    required: true
  }
})
// 顶部返回按钮
const onClickLeft = () =>{
  router.push({
    name: 'home' 
  })
}
//设置存储商品信息
const productsDetails = ref({})
// 获取商品详情信息
const initProductDetails = async (productId) => {
  const { data }= await getProductsDetails(productId)
  console.log(data)
  if(data.status !== 200) {
    // 找不到对应的商品直接跳转回首页
    return router.push({name: 'home'})
  }
  productsDetails.value = data.data
  // 初始化规格的初始数据
  initSpec(data.data.productAttr)
}
initProductDetails(productId)
//存储轮播图片信息
const storeInfo = computed(() => productsDetails.value.storeInfo) 
const swiperImgs = computed(() =>storeInfo.value?.slider_image)


// 存储好评个数
const commentCounts = computed(() => productsDetails.value.replyCount || 0) 
const userCounts = computed(() => `用户评价(${commentCounts.value})`) 
// 存储好评率
const commentRate = computed(() => productsDetails.value.replyChance || 0) 
const goodRate = computed(() => `好评率(${commentRate.value})`) 

// 存储回复
const reply = computed(() => productsDetails.value.reply)


// 存储推荐商品
const recommendGoods = computed(() => productsDetails.value?.good_list)

// 跳转页面后刷新整个页面并且重新请求数据
onBeforeRouteUpdate((to) => {
  // 清除旧数据
  productsDetails.value = {}
  // 回到顶部
  document.body.scrollTop = 0
  document.documentElement.scrollTop = 0
  // 根据新的id重新请求数据
  // console.log(to.params.productId)
  initProductDetails(to.params.productId)
})



// 规格弹出层处理 
const productAttr = computed(() => productsDetails.value?.productAttr)
const productValue = computed(() => productsDetails.value?.productValue)

// 变量状态 数据获取 
const specStatus = ref({
  // 弹出层的显示状态
  show: false,    
  // 选中的规格数据
  spec: [],
  // 购买个数
  buyCount: 0
})
// 显示或者隐藏弹出层
const handlePopup = () => {
  specStatus.value.show = true
}
// 初始化规格的默认选中数据
const initSpec = (spec) => {
  specStatus.value.spec = spec.map(item => item.attr_values[0])
}
// 规格切换处理
const handTag = (value, index) => {
  specStatus.value.spec[index] = value
}
// sku数据处理
const sku = computed(() => specStatus.value.spec.toString())
// 根据 sku 获取对用的商品信息  相当于是对 对象的遍历 根据sku得到对应的对象
const specDetail = computed(() =>productValue.value?.[sku.value])


// 加入购物车处理
const carttStatus = ref({
  isAdd: true
})
const handleAdd = async () =>{
  // 检测用户是否登录如果没有登录跳转登陆页面（store，router）
  if(!store.state.user){
    return router.push({
      name: 'login',
      query: {
        redirect: router.currentRoute.value.fullPath
      }
    })
  }
  // 如果登陆了判断弹框是否显示，如果没有显示就让它显示
  if (!specStatus.value.show){
    return specStatus.value.show = true
  }
  const { data } = await addCart({
    // new：提交状态，0 为加入购物车，1 为立即购买
    new: 0,
    // sku ID
    uniqueId: specDetail.value.unique,
    // 商品 ID
    productId: productId,
    // 加入个数
    cartNum: specStatus.value.buyCount
  })
  // console.log(data)
  if (data.status !== 200) {return}
  // 隐藏弹出框
  specStatus.value.show = false
  Toast('已加入购物车')
}


</script>
<style lang='scss' scoped>
.van-nav-bar{
  position: fixed !important;
}
// 商品信息部分
.van-tabs{
  padding-top: 46px;
  background-color: #f7f7f7;
  // 顶部tabs标题部分
  :deep(.van-tabs__wrap) {
  position: fixed;
  top: 0;
  z-index: 999;
  margin-left:50px;
  width: 80%;
  }
  // 轮播图
  .van-swipe-item img{
  width: 375px;
  }
  // 商品信息部分
  .salesInfo {
    margin-bottom: 10px;
  }
// title插槽
.van-cell__title {
    .price{
      span {
        font-size: 22px;
        font-weight: 700;
      }
      .share{
        float: right;
      }
    }
    .title{
      font-size: 16px;
      font-weight: 600;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient:vertical;
      overflow: hidden;
      margin:5px 0 10px
    }
}
// label插槽
:deep(.van-cell__label) {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}
.sku-window{
  margin-bottom: 10px;
}
}
// 商品评价部分

//商品推荐部分
.recommend{
  margin-bottom: 10px;
  :border
  .title{
    font-size: 20px;
    font-weight: 700;
  }
  .van-grid{
    padding: 5px 0;
    :deep(image){
      width: 100px;
      height: 100px;
    }
    p{
      font-size:12px;
      color:#666;
      font-weight: 600;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient:vertical;
      overflow: hidden;
    }
    span{
      color:#f76e13;
      font-size: 12px;
      font-weight: 600;
      // align-self: flex-start;
    }
  }
}
// 商品详情
.description{
  width: 100%;
  margin-bottom: 50px;
  :deep(img){
    width: 100%;
  }
}
// 弹出层提示
:deep(.van-popup){
  border-radius: 15px;
  max-height: 70%;
  .van-cell-group{
    margin-bottom: 50px;
    // 头部商品信息
    .pop-header{
      .van-cell__value{
        display: flex;
        img{
          width: 70px;
          height: 70px;
          align-self: center;
        }
        .info{
          padding: 8px;
          .title {
            font-size: 16px;
            font-weight: 600;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            overflow: hidden;
            -webkit-line-clamp: 1;
            margin-bottom: 10px;
          }
          .price{
            color:#f56607;
            font-size: 16px;
            font-weight: 600;
          }
          .stock{
            color:#888;
            font-size: 14px;
            font-weight: 600;
          }
        }
      }
    }
    // 规格选择
    .spec{
      p{
        font-size: 16px;
        font-weight: 600;
        margin: 5px 0;
      }
      .tag{
        display: inline-block;
        min-width: 25px;
        margin: 0 5px;
        padding: 0px 12px;
        border: 1px solid #ccc;
        border-radius: 20px;
        text-align: center;
        background-color: #f2f2f2;
      }
      .tag.active{
        border-color:#f75555;
        background-color: #f5dcdc;
        color:red
      }
    }
  }
}
// 加入购物车
.van-action-bar{
  z-index: 8000
}
</style>